package com.example.riseofthedefender;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.PointF;
import android.util.FloatMath;

public class SwordThing {

	public static float range = 220;
	public static int swingDuration = 10;
	public static float swingArch = 120;
	public static float arch = 30;

	
//	public static float range = 250;
//	public static int swingDuration = 30;
//	public static float swingArch = 360;
//	public static float arch = 30;
	
	public static float curRot_D = 0;
	public static float startRot_D = 0;
	public static boolean swingRight = true;
	public static PointF pos = new PointF();
	public static PointF forwardVector = new PointF();
	public static int duration = 0;
	private static Ball b;

	public static void swing(){
		duration = swingDuration;
		startRot_D = GameVar.touchAngleD;
		swingRight = (GameVar.touchVector.x>=0)?true:false;
		curRot_D = ((swingArch - arch) * 0.5f) * ((duration - swingDuration * 0.5f)/(swingDuration * 0.5f)) * (swingRight?1:-1);
		MyMath.NormVectorFromDegree(forwardVector, startRot_D+curRot_D);
	}
	
	public static void update(PointF startPos) {
		if (duration <= 0)
			return;

		curRot_D = ((swingArch - arch) * 0.5f) * ((duration - swingDuration * 0.5f)/(swingDuration * 0.5f)) * (swingRight?1:-1);
		MyMath.NormVectorFromDegree(forwardVector, startRot_D+curRot_D);
		pos.set(startPos.x + Player.Player_wHlv, startPos.y + Player.Player_hHlv);
		
		for (int i = 0; i < Ball.arrayList.size(); ++i) {
			b = Ball.arrayList.get(i);		
			testPosition.set(b.pos);
			if (checkCollisionArcToCircle(b.wHlv)){
				b.pos.y += GameVar.cHeight;
			}
		}
	}

	private static PointF testPosition = new PointF();
	
	public static boolean checkCollisionArcToCircle(float testRadius) {
		float distance = MyMath.distance(pos, testPosition);
		if (distance < testRadius) {
			return true;
		} else {
			if (distance < range + testRadius) {
				float toBallAngle = MyMath.angleR(pos, testPosition);
				PointF toBallVector = new PointF(FloatMath.cos(toBallAngle), FloatMath.sin(toBallAngle));
				float dot = MyMath.dot(forwardVector, toBallVector);
				float addAngle = FloatMath.sin(testRadius / distance) * MyMath.R2D;
				if (Math.acos(dot) * MyMath.R2D < arch * 0.5f + addAngle) {
					return true;
				}
			}
		}
		return false;
	}

	public static void draw(GL10 gl) {
		if (duration <= 0)
			return;
		float newX = pos.x + forwardVector.x * range * 0.5f;
		float newY = pos.y + forwardVector.y * range * 0.5f;

		gl.glLoadIdentity();

		gl.glTranslatef(-Camera.pos.x,-Camera.pos.y,0.0f);
		gl.glTranslatef(newX, newY, 0.0f);
		gl.glRotatef(startRot_D + curRot_D, 0, 0, 1);
		gl.glScalef(range * 0.5f, range, 1.0f);

		gl.glBindTexture(GL10.GL_TEXTURE_2D,TextureManager.WEAPON30[(duration%3)].textures[0]);
		
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, Square.vertices.length / 3);

		--duration;
	}
}
